import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:dio/dio.dart';
import '../model/custome_router.dart'; // 自定义路由切换动画
import '../model/config.dart'; // 全局配置文件
import '../model/my_store.dart'; // 本地数据存储

import '../widget/commit/my_appbar.dart'; // 自定义AppBar组件
import './home_page.dart'; // HomePage组件
class Login extends StatefulWidget {
  Login({
    Key key,
    this.setTheme
  }):super(key: key);
  dynamic setTheme;
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  bool loadtype; // 请求登录的状态
  final testUsernameController = TextEditingController(); // 账户名输入框控制器
  final testPasswordController = TextEditingController(); // 密码输入框控制器
  Color btnColor; // 按钮背景颜色
  @override
  void initState(){
    super.initState();
    loadtype = false; // 默认是没有加载登录的
    btnColor = null;
    // btnColor = Theme.of(context).primaryColor; // 默认颜色
  }
  @override
  void dispose () { // 销毁控制器，减少消耗
    testUsernameController.dispose();
    testPasswordController.dispose();
    super.dispose();
  }

  @override
  // 按钮的文本
  String loadtext () {
    if (loadtype) {
      return ' 登陆中...';
    } else {
      return '登 录';
    }
  }

  void startLogin () {
    FocusScope.of(context).requestFocus(FocusNode());
    if (loadtype) return;
    if (testUsernameController.text != '' && testPasswordController.text != '') {
      setState(() {loadtype = true;});
      Dio().post(
        MyConfig().baseurl + '/login/login',
        data: {
          'adminLogin' : false,
          'type' : 1005,
          'username' : testUsernameController.text,
          'pwd' : testPasswordController.text,
        }
      ).then((response) {
        if (response.statusCode == 200) {
          if (response.data['status'] == 1) {
            Map _loginInfo = {
              'id': response.data['user_info']['id'],
              'key': response.data['key'],
              'username' : testUsernameController.text,
              'pwd' : testPasswordController.text,
            };
            MyStore().setData('LOGININFO', _loginInfo);
            MyStore().setData('CSUSER${_loginInfo['id']}', response.data['user_info']);
            Map _csuserList = MyStore().getData('CSUSERLIST');
            if (_csuserList == null) _csuserList = {};
            _csuserList['cs${_loginInfo['id']}'] = {
              'header_url': response.data['user_info']['header_url'],
              'nickname' : response.data['user_info']['nickname'],
              'username' : testUsernameController.text,
              'pwd' : testPasswordController.text,
            };
            MyStore().setData('CSUSERLIST', _csuserList);
            setState(() {loadtype = false;});
            Navigator.of(context).pushReplacement(CustomeRouter(
              HomePage(
                setTheme: widget.setTheme,
              )
            ));
          }
        } 
      }).catchError((err){
        setState(() {loadtype = false;});
      });
    }  
  }

  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: PreferredSize(
        child: MyAppBar(
          brightness: true,
          title: '登  录',
        ),
        preferredSize: Size.fromHeight(ScreenUtil().setWidth(80)),
      ),
      body: Container(
        color: Color.fromRGBO(230, 230, 230, 1),
        child: ListView(
          children: <Widget>[
            SizedBox(
              height: ScreenUtil().setWidth(28),
            ),
            Form( // 表单
              child: Column(
                children: <Widget>[
                  TextFormField(
                    controller: testUsernameController,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      focusedBorder: InputBorder.none,
                      counterStyle: TextStyle(
                        fontSize: ScreenUtil().setWidth(20),
                      ),
                      hintText: '客服账号',
                      contentPadding: EdgeInsets.only(
                        top: ScreenUtil().setWidth(20),
                        left: ScreenUtil().setWidth(28),
                        right: ScreenUtil().setWidth(28),
                        bottom: ScreenUtil().setWidth(20),
                      ),
                      fillColor: Colors.white,
                      filled: true,
                    )
                  ),
                  Container(
                    height: 1,
                  ),
                  TextFormField(
                    controller: testPasswordController,
                    obscureText: true,
                    decoration: InputDecoration(
                      focusedBorder: InputBorder.none,
                      border: InputBorder.none,
                      counterStyle: TextStyle(
                        fontSize: ScreenUtil().setWidth(20),
                      ),
                      hintText: '密码',
                      contentPadding: EdgeInsets.only(
                        top: ScreenUtil().setWidth(20),
                        left: ScreenUtil().setWidth(28),
                        right: ScreenUtil().setWidth(28),
                        bottom: ScreenUtil().setWidth(20),
                      ),
                      fillColor: Colors.white,
                      filled: true,
                    )
                  ),
                  GestureDetector(
                    child: Container(
                      margin: EdgeInsets.all(ScreenUtil().setWidth(28)),
                      height: ScreenUtil().setWidth(80),
                      decoration: BoxDecoration(
                        color: btnColor == null ? Theme.of(context).primaryColor : btnColor,
                        borderRadius: BorderRadius.circular(ScreenUtil().setWidth(5))
                      ),
                      child: Center(
                        child: Text(
                          loadtext(),
                          style:TextStyle(
                            fontSize: ScreenUtil().setWidth(28),
                            color: Theme.of(context).primaryTextTheme.title.color
                          )
                        ),
                      ),
                    ),
                    onTapDown: (details) {  
                      setState(() {btnColor = Theme.of(context).primaryColorDark;});
                    },
                    onTapUp: (details) {
                      setState(() {btnColor = Theme.of(context).primaryColor;});
                    },
                    onTapCancel: () {
                      setState(() {btnColor = Theme.of(context).primaryColor;});
                    },
                    onTap: startLogin,
                  )
                ],
              )
            )
          ],
        ),
      ),
    );
  }
}